<?php

namespace app\common\model;

use think\Model;

class UserBind extends Model
{
    // 表名
    protected $name = 'user_bind';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text',
	    'status_text'
    ];
    

    const STATUS_Y = 1;
    const STATUS_N = 0;

    public static $statusList = [
        self::STATUS_Y => '正常',
	    self::STATUS_N => '已解绑'
    ];
    
    public function getStatusTextAttr($value, $data) {
    	$value = $value ? $value : $data['status'];
        $list = self::$statusList;
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
	
	/**
	 * 绑定用户
	 * @param $userId 用户ID
	 * @param $targetUserId 绑定用户ID
	 * @param $remark 备注名称
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    public function bindUser($userId, $targetUserId, $remark) {
    	$row = $this->where(['user_id' => $userId, 'target_user_id' => $targetUserId])
		    ->find();
    	
    	if($row && $row['status'] == self::STATUS_Y) {
    		$this->error = '你已经绑定该用户了';
    		return false;
	    } else if($row) {
    	    $res = $this->save(['status' => self::STATUS_Y, 'remark' => $remark], ['id' => $row['id']]);
	    } else {
    		$res = $this->isUpdate(false)->save([
    			'user_id' => $userId,
			    'target_user_id' => $targetUserId,
			    'remark' => $remark
		    ]);
	    }
	    
	    if($res) {
	        return true;
	    } else {
	    	$this->error = '绑定出错，请稍候重试';
	    	return false;
	    }
	    
    }
}
